import mongodbHandle from '../handle/mongodbHandle'
import * as moment from 'moment'
import app from '../app'
import utils from '../core/utils'
import redisHandle from './redisHandle'
import * as schedule from 'node-schedule'
import * as cluster from 'cluster'
import { gameConfig } from 'js/config/gameConfig'

var ObjectId = require('mongodb').ObjectId;
var equipmentList = ["e1", "e2", "e3", "e4",
    "e5", "e6", "e7", "e8",
    "e9", "e10", "e11", "e12", "e13"]

var RankDay = -300
class RankHandle {
    powerRankData: any
    powerRankArray: any
    equipmentPowerRankData: any
    equipmentPowerRankArray: any
    arenaRankData: any
    arenaRankArray: any
    mapProgressRankData: any
    mapProgressRankArray: any
    devilProgressRankData: any
    devilProgressRankArray: any
    worldBossRankData: any
    worldBossRankArray: any
    deepProgressRankData: any
    deepProgressRankArray: any
    nightProgressRankData: any
    nightProgressRankArray: any
    boomingRankData: any
    boomingRankArray: any
    boomingReward: any
    run: boolean
    constructor() {
        this.powerRankData = {} //总战斗力
        this.powerRankArray = {}
        this.arenaRankData = {}
        this.arenaRankArray = {}
        this.mapProgressRankData = {}
        this.mapProgressRankArray = {}
        this.devilProgressRankData = {}
        this.devilProgressRankArray = {}
        this.worldBossRankData = {}
        this.worldBossRankArray = {}
        this.equipmentPowerRankData = {}
        this.equipmentPowerRankArray = {}
        this.deepProgressRankData = {}
        this.deepProgressRankArray = {}
        this.nightProgressRankData = {}
        this.nightProgressRankArray = {}
        this.boomingRankData = {}
        this.boomingRankArray = {}
        this.boomingReward = {}
        this.run = false
    }
    init = async () => {
        // await redisHandle.init()
        if (app.env !== 'adminPro') {
            // await this.initPowerRank()
            // await this.initArenaRank()

            // await this.initWorldBossRank()
            setTimeout(() => {
                this.initMapProgressRank()
                this.initDeepProgressRank()
                this.initPowerRank()
                this.initNightProgressRank()
                this.initBoomingRank()
                this.createBoomingRankReward()

            }, 3000)
            // setTimeout(() => {
            //     this.createNightProgressRankReward()
            // }, 60000)
            setInterval(async () => {
                if (app.env !== 'adminPro') {
                    console.log(`${cluster.isMaster ? 'master' : 'id' + cluster.worker.id}  rankStart`)
                    // if (rankHandle.run == false) {
                    //     await rankHandle.initEquipmentPowerRank()
                    // }
                    if (rankHandle.run == false) {
                        await rankHandle.initPowerRank()
                    }
                    if (rankHandle.run == false) {
                        await rankHandle.initDeepProgressRank()
                    }
                    // if (rankHandle.run == false) {
                    //     await rankHandle.initArenaRank()
                    // }
                    if (rankHandle.run == false) {
                        await rankHandle.initMapProgressRank()
                    }

                    if (rankHandle.run == false) {
                        await rankHandle.initBoomingRank()
                    }

                    if (rankHandle.run == false) {
                        await rankHandle.initNightProgressRank()
                    }
                    // if (rankHandle.run == false) {
                    //     await rankHandle.initDevilProgressRank()
                    // }
                    // if (rankHandle.run == false) {
                    //     await rankHandle.initWorldBossRank()
                    // }
                    console.log(`${cluster.isMaster ? 'master' : 'id' + cluster.worker.id}  rankEnd`)
                }
            }, 10 * 60 * 1000)
        }
    }


    schedule = () => {
        console.log('schedule任务')
        schedule.scheduleJob('0 0 20 * * *', async () => {
            rankHandle.run = true
            await this.createPowerRankReward()
            rankHandle.run = false
        });
        schedule.scheduleJob('0 0 21 * * *', async () => {
            rankHandle.run = true
            await this.createMapProgressRankReward(app.env)
            rankHandle.run = false
        });
        // schedule.scheduleJob('0 0 22 * * *', async () => {
        //     rankHandle.run = true
        //     await this.createDevilProgressRankReward(app.env)
        //     rankHandle.run = false
        // });
        schedule.scheduleJob('0 0 23 * * 6', async () => {
            rankHandle.run = true
            await this.createDeepProgressRankReward(app.env)
            rankHandle.run = false
        });

        schedule.scheduleJob('0 59 23 * * *', async () => {
            rankHandle.run = true
            await this.createBoomingRankReward()
            rankHandle.run = false
        });
        // schedule.scheduleJob('0 0 23 * * 6', async () => {
        //     rankHandle.run = true
        //     await this.createArenaRankReward()
        //     rankHandle.run = false
        // });

        schedule.scheduleJob('0 0 22 * * *', async () => {
            rankHandle.run = true
            await this.createNightProgressRankReward()
            rankHandle.run = false
        });
        // schedule.scheduleJob('10 * * * * *', async () => {
        //     rankHandle.run = true
        //     await this.createDeepProgressRankReward(app.env)
        //     rankHandle.run = false
        // });
    }

    getServerList = async () => {
        let docs = await mongodbHandle.serverDao.find({
            active: true
        })
        let serverList = {}
        for (let i = 0; i < docs.length; i++) {
            let serverID = docs[i].newServerID
            serverList[serverID] = true
        }
        let servers: number[] = []
        Object.keys(serverList).forEach((item, i) => {
            servers[i] = Number(item)
        })
        return servers
    }
    initPowerRank = async () => {
        this.powerRankData = {}
        this.powerRankArray = {}
        let time = moment().add(RankDay, 'days').valueOf()
        let serverList = await this.getServerList()
        let phones = ["android", "ios"]
        console.log('战力排行列表_' + JSON.stringify(serverList), serverList.length)
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            this.powerRankArray[serverID] = []
            this.powerRankData[serverID] = {}
            let docs = await mongodbHandle.playerDao.findByPageAndSort({
                currentServerID: Number(serverID),
                "cheat": false,
                "totalPower": {
                    $gt: 10000
                },
            }, {
                "totalPower": -1
            }, 0, 300)
            console.log('战力排行_' + serverID, docs.length)
            for (let i = 0; i < docs.length; i++) {
                let doc = docs[i]
                let data = {
                    rank: i + 1,
                    id: doc.id,
                    pID: doc._id.toString(),
                    value: doc.totalPower,
                    name: doc.playerData ? doc.playerData.playerName : '',
                }
                this.powerRankArray[serverID].push(data);
                this.powerRankData[serverID][doc._id.toString()] = data
            }
        }
    }



    initArenaRank = async () => {
        this.arenaRankData = {}
        this.arenaRankArray = {}
        let time = moment().add(RankDay, 'days').valueOf()
        let serverList = await this.getServerList()
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            this.arenaRankArray[serverID] = []
            this.arenaRankData[serverID] = {}
            let docs = await mongodbHandle.playerDao.findByPageAndSort({
                currentServerID: serverID,
                "cheat": false,
                "loginTime": {
                    $gt: time
                },
            }, {
                "arenaPoint": -1
            }, 0, 100)
            for (let i = 0; i < docs.length; i++) {
                let doc = docs[i]
                let player = doc.playerData
                let team: number[] = []
                if (player.Team) {
                    if (player.BasicInfo.PvP) {
                        player.Team.forEach((partner) => {
                            if (partner) {
                                team[partner.PVPBattlePos] = partner.PVPTID
                            }
                        })
                    } else {
                        player.Team.forEach((partner) => {
                            if (partner) {
                                team.push(partner.TID)
                            }
                        })
                    }
                }
                let data = {
                    rank: i + 1,
                    id: doc.id,
                    pID: doc._id.toString(),
                    value: doc.arenaPoint,
                    name: doc.playerData ? doc.playerData.playerName : '',
                    team: team
                }
                this.arenaRankArray[serverID].push(data);
                this.arenaRankData[serverID][doc._id.toString()] = data
            }
        }
    }

    initMapProgressRank = async () => {
        this.mapProgressRankData = {}
        this.mapProgressRankArray = {}
        let serverList = await this.getServerList()
        let time = moment().add(RankDay, 'days').valueOf()
        let phones = ["android", "ios"]
        console.log(`冒险排行服务器: ${serverList.length}个`,)
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            this.mapProgressRankData[serverID] = {}
            this.mapProgressRankArray[serverID] = []
            let docs = await mongodbHandle.playerDao.findByPageAndSort({
                currentServerID: serverID,
                "cheat": false,
                "mapProgressMax": {
                    $gte: 1003500000000
                },
            }, {
                "mapProgressMax": -1
            }, 0, 300)
            console.log(`${serverID}服冒险排行: ${docs.length}人`)
            for (let i = 0; i < docs.length; i++) {
                let doc = docs[i]
                let data = {
                    rank: i + 1,
                    id: doc.id,
                    pID: doc._id.toString(),
                    value: doc.mapProgressMax,
                    name: doc.playerData ? doc.playerData.playerName : '',
                }
                this.mapProgressRankArray[serverID].push(data);
                this.mapProgressRankData[serverID][doc._id.toString()] = data
            }


        }
    }

    initDevilProgressRank = async () => {
        this.devilProgressRankData = {}
        this.devilProgressRankArray = {}
        let serverList = await this.getServerList()
        let time = moment().add(RankDay, 'days').valueOf()
        let phones = ["android", "ios"]
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            this.devilProgressRankData[serverID] = {}
            this.devilProgressRankArray[serverID] = []
            let docs = await mongodbHandle.playerDao.findByPageAndSort({
                currentServerID: serverID,
                "cheat": false,
                "devilProgressMax": {
                    $gte: 100000000
                },
            }, {
                "devilProgressMax": -1
            }, 0, 100)
            for (let i = 0; i < docs.length; i++) {
                let doc = docs[i]
                let data = {
                    rank: i + 1,
                    id: doc.id,
                    pID: doc._id.toString(),
                    value: doc.devilProgressMax,
                    name: doc.playerData ? doc.playerData.playerName : '',
                }
                this.devilProgressRankArray[serverID].push(data);
                this.devilProgressRankData[serverID][doc._id.toString()] = data
            }
        }
    }

    initDeepProgressRank = async () => {
        this.deepProgressRankData = {}
        this.deepProgressRankArray = {}
        let serverList = await this.getServerList()
        let weekDay = Math.floor((moment().startOf('day').valueOf() - 1686412800000) / (7 * 24 * 60 * 60 * 1000))
        let time = moment().add(RankDay, 'days').valueOf()
        let phones = ["android", "ios"]
        console.log('战力排行列表_' + JSON.stringify(serverList), serverList.length)
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            this.deepProgressRankData[serverID] = {}
            this.deepProgressRankArray[serverID] = []
            let docs = await mongodbHandle.playerDao.findByPageAndSort({
                currentServerID: serverID,
                "cheat": false,
                "deepProgress": {
                    $gte: 10
                },
            }, {
                "deepProgress": -1
            }, 0, 300)
            console.log('深渊排行_' + serverID, docs.length)
            for (let i = 0; i < docs.length; i++) {
                let doc = docs[i]
                let data = {
                    rank: i + 1,
                    id: doc.id,
                    pID: doc._id.toString(),
                    value: doc.deepProgress,
                    name: doc.playerData ? doc.playerData.playerName : '',
                }
                this.deepProgressRankArray[serverID].push(data);
                this.deepProgressRankData[serverID][doc._id.toString()] = data
            }
        }
    }

    initNightProgressRank = async () => {
        this.nightProgressRankArray = {}
        this.nightProgressRankData = {}
        let serverList = await this.getServerList()
        let weekDay = Math.floor((moment().startOf('day').valueOf() - 1686412800000) / (7 * 24 * 60 * 60 * 1000))
        let time = moment().add(RankDay, 'days').valueOf()
        let phones = ["android", "ios"]
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            this.nightProgressRankData[serverID] = {}
            this.nightProgressRankArray[serverID] = []
            let docs = await mongodbHandle.playerDao.findByPageAndSort({
                currentServerID: serverID,
                "cheat": false,
                "nightProgress": {
                    $gte: 10
                },
            }, {
                "nightProgress": -1
            }, 0, 50)
            for (let i = 0; i < docs.length; i++) {
                let doc = docs[i]
                let data = {
                    rank: i + 1,
                    id: doc.id,
                    pID: doc._id.toString(),
                    value: doc.nightProgress,
                    name: doc.playerData ? doc.playerData.playerName : '',
                }
                this.nightProgressRankArray[serverID].push(data);
                this.nightProgressRankData[serverID][doc._id.toString()] = data
            }
        }
    }

    initBoomingRank = async () => {
        this.boomingRankArray = {}
        this.boomingRankData = {}
        let serverList = await this.getServerList()
        let weekDay = Math.floor((moment().startOf('day').valueOf() - 1686412800000) / (7 * 24 * 60 * 60 * 1000))
        let today = moment().startOf('day').valueOf()
        let time = moment().add(RankDay, 'days').valueOf()
        let phones = ["android", "ios"]
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            this.boomingRankData[serverID] = {}
            this.boomingRankArray[serverID] = []
            let docs = await mongodbHandle.playerDao.findByPageAndSort({
                currentServerID: serverID,
                "cheat": false,
                "booming": {
                    $gte: 2000
                },
                "playerData.baseInfo.saveTime": { $gte: today }
            }, {
                "booming": -1
            }, 0, 10)
            let boomingCheck = {
                1: 6,
                2: 19,
                3: 40,
                4: 70,
                5: 110,
                6: 161,
                7: 224,
                8: 300,
                9: 390,
                10: 495
            }
            for (let i = 0; i < docs.length; i++) {
                let doc = docs[i]
                let lvl = 0
                if (doc.playerData.townInfo) {
                    lvl = doc.playerData.townInfo.lvl || 0
                }
                let usedItem = doc.playerData.itemInfo.usedItemStat[170008]
                let needUsedItem = boomingCheck[lvl] || 0
                let isCheat = true
                if ((usedItem < needUsedItem || lvl == 0) && !doc.unCheckTown) {
                    // let testCheat = doc.playerData.info.cheat > 0
                    // if (testCheat) {
                    //     isCheat = false
                    // }
                    await mongodbHandle.cheatDao.newAndSave4(doc.uID, doc._id.toString(), lvl, doc.booming, usedItem, needUsedItem)
                    await mongodbHandle.playerDao.updateOne({
                        _id: doc._id,
                    }, {
                        $set: {
                            cheat: isCheat,
                        }
                    })
                }
                let data = {
                    rank: i + 1,
                    id: doc.id,
                    pID: doc._id.toString(),
                    value: doc.booming,
                    name: doc.playerData ? doc.playerData.playerName : '',
                }
                this.boomingRankArray[serverID].push(data);
                this.boomingRankData[serverID][doc._id.toString()] = data
            }
        }
    }

    getBoomingRank(serverID, phone) {
        if (this.boomingRankArray && this.boomingRankArray[serverID]) {
            return this.boomingRankArray[serverID]
        } else {
            return []
        }
    }

    getBoomingRankByPID(serverID, phone, pid) {
        if (this.boomingRankData && this.boomingRankData[serverID]) {
            let d = this.boomingRankData[serverID][pid]
            if (d) {
                return {
                    rank: d.rank,
                    value: d.value
                }
            } else {
                return null
            }
        } else {
            return null
        }
    }

    getNightProgressRankByPID(serverID, phone, pid) {
        if (this.nightProgressRankData && this.nightProgressRankData[serverID]) {
            let d = this.nightProgressRankData[serverID][pid]
            if (d) {
                return {
                    rank: d.rank,
                    value: d.value
                }
            } else {
                return null
            }
        } else {
            return null
        }
    }

    getNightProgressRank(serverID, phone) {
        if (this.nightProgressRankArray && this.nightProgressRankArray[serverID]) {
            return this.nightProgressRankArray[serverID]
        } else {
            return []
        }
    }


    getPowerRankByPID(serverID, phone, pid) {
        if (this.powerRankData && this.powerRankData[serverID]) {
            let d = this.powerRankData[serverID][pid]
            if (d) {
                return {
                    rank: d.rank,
                    value: d.value
                }
            } else {
                return null
            }
        } else {
            return null
        }
    }

    getPowerRank(serverID, phone) {
        if (this.powerRankArray && this.powerRankArray[serverID] && this.powerRankArray[serverID]) {
            return this.powerRankArray[serverID]
        } else {
            return []
        }
    }

    getEquipmentPowerRankByPID(serverID, pid, phone, equipmentLabel) {
        if (this.equipmentPowerRankData && this.equipmentPowerRankData[serverID]
            && this.equipmentPowerRankData[serverID][phone] && this.equipmentPowerRankData[serverID][phone][equipmentLabel]) {
            let d = this.equipmentPowerRankData[serverID][phone][equipmentLabel][pid]
            if (d) {
                return {
                    rank: d.rank,
                    value: d.value
                }
            } else {
                return null
            }
        } else {
            return null
        }
    }


    getEquipmentPowerRank(serverID, phone, equipmentLabel) {
        if (this.equipmentPowerRankArray[serverID] && this.equipmentPowerRankArray[serverID][phone] && this.equipmentPowerRankArray[serverID][phone][equipmentLabel]) {
            return this.equipmentPowerRankArray[serverID][phone][equipmentLabel]
        }
    }

    getArenaRankByPID(serverID, pid) {
        if (this.arenaRankData && this.arenaRankData[serverID]) {
            let d = this.arenaRankData[serverID][pid]
            if (d) {
                return {
                    rank: d.rank,
                    value: d.value
                }
            } else {
                return null
            }
        } else {
            return null
        }
    }

    getArenaRank(serverID) {
        return this.arenaRankArray[serverID]
    }

    getMapProgressRank = (serverID, phone) => {
        if (this.mapProgressRankArray && this.mapProgressRankArray[serverID]) {
            return this.mapProgressRankArray[serverID]
        } else {
            return []
        }
    }

    getMapProgressRankByPID = (serverID, phone, pid) => {
        if (this.mapProgressRankData && this.mapProgressRankData[serverID] && this.mapProgressRankData[serverID]) {
            let d = this.mapProgressRankData[serverID][pid]
            if (d) {
                return {
                    rank: d.rank,
                    value: d.value
                }
            } else {
                return null
            }
        } else {
            return null
        }
    }


    getDevilProgressRank = (serverID, phone) => {
        if (this.devilProgressRankArray && this.devilProgressRankArray[serverID] && this.devilProgressRankArray[serverID]) {
            return this.devilProgressRankArray[serverID]
        } else {
            return []
        }
    }

    getDevilProgressRankByPID = (serverID, phone, pid) => {
        if (this.devilProgressRankData && this.devilProgressRankData[serverID] && this.devilProgressRankData[serverID]) {
            let d = this.devilProgressRankData[serverID][pid]
            if (d) {
                return {
                    rank: d.rank,
                    value: d.value
                }
            } else {
                return null
            }
        } else {
            return null
        }
    }

    getDeepProgressRank = (serverID, phone) => {
        if (this.deepProgressRankArray && this.deepProgressRankArray[serverID] && this.deepProgressRankArray[serverID]) {
            return this.deepProgressRankArray[serverID]
        } else {
            return []
        }
    }

    getBoomingRankReward = (serverID, phone) => {
        if (this.boomingReward && this.boomingReward[serverID]) {
            return this.boomingReward[serverID]
        } else {
            return {}
        }
    }

    getDeepProgressRankByPID = (serverID, phone, pid) => {
        if (this.deepProgressRankData && this.deepProgressRankData[serverID] && this.deepProgressRankData[serverID]) {
            let d = this.deepProgressRankData[serverID][pid]
            if (d) {
                return {
                    rank: d.rank,
                    value: d.value
                }
            } else {
                return null
            }
        } else {
            return null
        }
    }


    createPowerRankReward = async () => {
        let serverList = await this.getServerList()
        let time = moment().add(RankDay, 'days').valueOf()
        let dateStr = moment().format('MM月DD号')
        let size = 500
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            console.log('战斗力' + serverID + '服')
            let length = size
            let page = 0
            let players = []
            while (length >= size) {
                let docs = await mongodbHandle.playerDao.findByPageAndSort({
                    currentServerID: Number(serverID),
                    "cheat": false,
                    "totalPower": {
                        $gt: 100
                    },
                    "mapProgressMax": {
                        $gt: 100000000000 + gameConfig.base.unlockOfRank * 100000000
                    },
                }, {
                    "totalPower": -1
                }, page * size, size)
                length = docs.length
                for (let i = 0; i < length; i++) {
                    let doc = docs[i]
                    let pID = doc._id.toString()
                    players.push([pID, doc.loginTime])
                }
                page += 1
            }
            let rankTime = moment().add(-7, 'days').valueOf()
            for (let i = 0; i < players.length; i++) {
                let rank = i
                let loginTime = players[i][1]
                if (loginTime > rankTime) {
                    let pID = players[i][0]
                    if (rank == 0) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}战斗力排名第${rank + 1}`, [["diamond", 300]], null)
                    } else if (rank >= 1 && rank <= 9) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}战斗力排名第${rank + 1}`, [["diamond", 250]], null)
                    } else if (rank >= 10 && rank <= 49) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}战斗力排名第${rank + 1}`, [["diamond", 200]], null)
                    } else if (rank >= 50 && rank <= 199) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}战斗力排名第${rank + 1}`, [["diamond", 150]], null)
                    } else {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}战斗力排名第${rank + 1}`, [["diamond", 100]], null)
                    }
                }
                if (i % 200 == 0) {
                    await utils.setTimeout(20)
                }
            }
        }
        console.log('战斗力结束')
    }

    createNightProgressRankReward = async () => {
        let serverList = await this.getServerList()
        let time = moment().add(RankDay, 'days').valueOf()
        let dateStr = moment().format('MM月DD号')
        let size = 500
        let weekDay = Math.floor((moment().startOf('day').valueOf() - 1686412800000) / (7 * 24 * 60 * 60 * 1000))
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            console.log('心魔' + serverID + '服')
            let length = size
            let page = 0
            let players = []
            while (length >= size) {
                let docs = await mongodbHandle.playerDao.findByPageAndSort({
                    currentServerID: Number(serverID),
                    "cheat": false,
                    "nightProgress": {
                        $gt: 1
                    }
                }, {
                    "nightProgress": -1,
                }
                    , page * size, size)
                length = docs.length
                for (let i = 0; i < length; i++) {
                    let doc = docs[i]
                    let pID = doc._id.toString()
                    players.push([pID, doc.loginTime])
                }
                page += 1
            }
            let rankTime = moment().add(-7, 'days').valueOf()
            for (let i = 0; i < players.length; i++) {
                let rank = i
                let loginTime = players[i][1]
                if (loginTime > rankTime) {
                    let pID = players[i][0]
                    if (rank == 0) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}心魔排名第${rank + 1}`, [["diamond", 200]], null)
                    } else if (rank >= 1 && rank <= 9) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}心魔排名第${rank + 1}`, [["diamond", 150]], null)
                    } else if (rank >= 10 && rank <= 49) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}心魔排名第${rank + 1}`, [["diamond", 100]], null)
                    } else if (rank >= 50 && rank <= 199) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}心魔排名第${rank + 1}`, [["diamond", 50]], null)
                    }
                }
                if (i % 200 == 0) {
                    await utils.setTimeout(20)
                }
            }
        }
        console.log('心魔结束')
    }

    createBoomingRankReward = async () => {
        let serverList = await this.getServerList()
        let time = moment().add(RankDay, 'days').valueOf()
        let dateStr = moment().format('MM月DD号')
        let size = 500
        let weekDay = Math.floor((moment().startOf('day').valueOf() - 1686412800000) / (7 * 24 * 60 * 60 * 1000))
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            console.log('城镇' + serverID + '服')
            this.boomingReward[serverID] = {}
            let aggregate = [
                {
                    $match: {
                        "cheat": false,
                        "currentServerID": serverID,
                        "booming": { $gt: 2000 },
                    }
                },
                {
                    $group: {
                        "_id": null,
                        totalBooming: { $sum: "$booming" }
                    }
                }
            ]
            let totalBooming = await mongodbHandle.playerDao.aggregate(aggregate)
            if (totalBooming && totalBooming.length > 0) {
                this.boomingReward[serverID]['booming'] = totalBooming[0].totalBooming
            } else {
                this.boomingReward[serverID]['booming'] = 0
            }

            let aggregate1 = [
                {
                    $match: {
                        "currentServerID": serverID,
                        "booming": { $gt: 2000 },
                    }
                },
                {
                    $group: {
                        "_id": null,
                        totalSaveScore: { $sum: "$playerData.townInfo.saveScore" }
                    }
                }
            ]
            let totalSaveScore = await mongodbHandle.playerDao.aggregate(aggregate1)
            if (totalSaveScore && totalSaveScore.length > 0) {
                this.boomingReward[serverID]['score'] = totalSaveScore[0].totalSaveScore
            } else {
                this.boomingReward[serverID]['score'] = 0
            }


            let totalPlayerCount = await mongodbHandle.playerDao.count({
                "currentServerID": serverID,
                "booming": { $gt: 2000 },
            })
            if (totalPlayerCount) {
                this.boomingReward[serverID]['count'] = totalPlayerCount
                let avgScore: any = 0
                if (this.boomingReward[serverID]['count'] && this.boomingReward[serverID]['score']) {
                    avgScore = Math.floor(this.boomingReward[serverID]['score'] / this.boomingReward[serverID]['count']).toFixed(0)
                }
                this.boomingReward[serverID]['avgScore'] = avgScore
            } else {
                this.boomingReward[serverID]['count'] = 0
                this.boomingReward[serverID]['avgScore'] = 0
            }
        }
        console.log('城镇结束')
    }

    createArenaRankReward = async () => {
        let time = moment().add(RankDay, 'days').valueOf()
        let serverList = await this.getServerList()
        let reward = app.config.reward.arenaPoint
        let dateStr = moment().format('MM月DD号')
        let size = 500
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]

            let length = size
            let page = 0
            let players = []
            console.log('竞技场' + serverID + '服')
            while (length >= size) {
                let docs = await mongodbHandle.playerDao.findByPageAndSort({
                    currentServerID: Number(serverID),
                    "cheat": false,
                    "loginTime": {
                        $gt: time
                    },
                }, {
                    "arenaScore": -1,
                }, page * size, size)
                length = docs.length
                for (let i = 0; i < length; i++) {
                    let doc = docs[i]
                    let pID = doc._id.toString()
                    players.push([pID, doc.loginTime])
                }
                page += 1
            }
            let rankTime = moment().add(-7, 'days').valueOf()
            for (let i = 0; i < players.length; i++) {
                let rank = i
                let loginTime = players[i][1]
                if (loginTime > rankTime) {
                    let pID = players[i][0]
                    if (rank == 0) {
                        //.寄语:没一个能打的
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}竞技排名第${rank + 1}奖励.寄语:没一个能打的`, [["diamond", 200], ["vipExp", 5]], null)
                    } else if (rank >= 1 && rank <= 9) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}竞技排名第${rank + 1}奖励`, [["diamond", 200], ["vipExp", 5]], null)
                    } else if (rank >= 10 && rank <= 49) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}竞技排名第${rank + 1}奖励`, [["diamond", 200], ["vipExp", 5]], null)
                    } else if (rank >= 50 && rank <= 199) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}竞技排名第${rank + 1}奖励`, [["diamond", 200], ["vipExp", 5]], null)
                    } else {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}竞技排名第${rank + 1}奖励`, [["diamond", 200], ["vipExp", 5]], null)
                    }
                }
                if (i % 200 == 0) {
                    await utils.setTimeout(20)
                }
            }
        }
        console.log('竞技场结束')
    }

    createMapProgressRankReward = async (env) => {
        let time = moment().add(RankDay, 'days').valueOf()
        let serverList = await this.getServerList()
        let dateStr = moment().format('MM月DD号')
        let size = 500
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            let length = size
            let page = 0
            let players = []
            console.log('竞技场' + serverID + '服')
            while (length >= size) {
                let docs = await mongodbHandle.playerDao.findByPageAndSort({
                    currentServerID: Number(serverID),
                    "cheat": false,
                    "mapProgressMax": {
                        $gt: 100000000000 + gameConfig.base.unlockOfRank * 100000000
                    },
                }, {
                    "mapProgressMax": -1,
                }, page * size, size)
                length = docs.length
                for (let i = 0; i < length; i++) {
                    let doc = docs[i]
                    let pID = doc._id.toString()
                    players.push([pID, doc.loginTime])
                }
                page += 1
            }
            let rankTime = moment().add(-7, 'days').valueOf()
            for (let i = 0; i < players.length; i++) {
                let rank = i
                let loginTime = players[i][1]
                if (loginTime > rankTime) {
                    let pID = players[i][0]
                    if (rank == 0) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}冒险进度排名第${rank + 1}.`, [["diamond", 300]], null)
                    } else if (rank >= 1 && rank <= 9) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}冒险进度排名第${rank + 1}`, [["diamond", 250]], null)
                    } else if (rank >= 10 && rank <= 49) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}冒险进度排名第${rank + 1}`, [["diamond", 200]], null)
                    } else if (rank >= 50 && rank <= 199) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}冒险进度排名第${rank + 1}`, [["diamond", 150]], null)
                    } else {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}冒险进度排名第${rank + 1}`, [["diamond", 100]], null)
                    }
                }
                if (i % 200 == 0) {
                    await utils.setTimeout(20)
                }
            }
        }
    }

    createDevilProgressRankReward = async (env) => {
        let time = moment().add(RankDay, 'days').valueOf()
        let serverList = await this.getServerList()
        let dateStr = moment().format('MM月DD号')
        let size = 500
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            let length = size
            let page = 0
            let players = []
            console.log('除魔' + serverID + '服')
            while (length >= size) {
                let docs = await mongodbHandle.playerDao.findByPageAndSort({
                    currentServerID: Number(serverID),
                    "cheat": false,
                    "devilProgressMax": {
                        $gte: 100000000
                    },
                }, {
                    "devilProgressMax": -1,
                }, page * size, size)
                length = docs.length
                for (let i = 0; i < length; i++) {
                    let doc = docs[i]
                    let pID = doc._id.toString()
                    players.push([pID, doc.loginTime])
                }
                page += 1
            }
            let rankTime = moment().add(-7, 'days').valueOf()
            for (let i = 0; i < players.length; i++) {
                let rank = i
                let loginTime = players[i][1]
                if (loginTime > rankTime) {
                    let pID = players[i][0]
                    if (rank == 0) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}除魔排名第${rank + 1}`, [["diamond", 300]], null)
                    } else if (rank >= 1 && rank <= 9) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}除魔排名第${rank + 1}`, [["diamond", 200]], null)
                    } else if (rank >= 10 && rank <= 49) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}除魔排名第${rank + 1}`, [["diamond", 150]], null)
                    } else if (rank >= 50 && rank <= 199) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}除魔排名第${rank + 1}`, [["diamond", 130]], null)
                    } else {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}除魔排名第${rank + 1}`, [["diamond", 100]], null)
                    }
                }
                if (i % 200 == 0) {
                    await utils.setTimeout(20)
                }
            }
        }
    }

    createDeepProgressRankReward = async (env) => {
        let time = moment().add(RankDay, 'days').valueOf()
        let serverList = await this.getServerList()
        let dateStr = moment().format('MM月DD号')
        let size = 500
        let weekDay = Math.floor((moment().startOf('day').valueOf() - 1686412800000) / (7 * 24 * 60 * 60 * 1000))
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            let length = size
            let page = 0
            let players = []
            console.log('深渊' + serverID + '服')
            while (length >= size) {
                let docs = await mongodbHandle.playerDao.findByPageAndSort({
                    currentServerID: Number(serverID),
                    "cheat": false,
                    "deepProgress": {
                        $gt: 1
                    },
                    "mapProgressMax": {
                        $gt: 100000000000 + gameConfig.base.unlockOfRank * 100000000
                    },
                }, {
                    "deepProgress": -1,
                }, page * size, size)
                length = docs.length
                for (let i = 0; i < length; i++) {
                    let doc = docs[i]
                    let pID = doc._id.toString()
                    players.push([pID, doc.loginTime])
                }
                page += 1
            }
            let rankTime = moment().add(-7, 'days').valueOf()
            for (let i = 0; i < players.length; i++) {
                let rank = i
                let loginTime = players[i][1]
                if (loginTime > rankTime) {
                    let pID = players[i][0]
                    if (rank == 0) {
                        //.寄语:没一个能打的
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}深渊排名第${rank + 1}`, [["diamond", 1000]], null)
                    } else if (rank >= 1 && rank <= 9) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}深渊排名第${rank + 1}`, [["diamond", 800]], null)
                    } else if (rank >= 10 && rank <= 49) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}深渊排名第${rank + 1}`, [["diamond", 500]], null)
                    } else if (rank >= 50 && rank <= 199) {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}深渊排名第${rank + 1}`, [["diamond", 300]], null)
                    } else {
                        await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}深渊排名第${rank + 1}`, [["diamond", 150]], null)
                    }
                }
                if (i % 200 == 0) {
                    await utils.setTimeout(20)
                }
            }
        }
    }

    createWorldBossRankReward = async (env) => {
        let serverList = await this.getServerList()
        let reward = app.config.reward.worldBoss
        let dateStr = moment().format('MM月DD号')
        for (let i = 0; i < serverList.length; i++) {
            let serverID = serverList[i]
            console.log('世界boss' + serverID + '服')
            let data = await redisHandle.zrevrange(app.config.gameName + 'worldBossRank' + serverID, 0, -1)
            for (let i = 0; i < data.length; i++) {
                let pID = data[i]
                // if (i == 0) {
                //     //.寄语:让我来毁灭一切
                //     await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}弑神排名第${i + 1}奖励.寄语:让我来毁灭一切`, [[reward[0], 1]], 0, 0)
                // } else if (i >= 1 && i <= 9) {
                //     await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}弑神排名第${i + 1}奖励`, [[reward[1], 1]], 0, 0)
                // } else if (i >= 10 && i <= 49) {
                //     await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}弑神排名第${i + 1}奖励`, [[reward[2], 1]], 0, 0)
                // } else if (i >= 50 && i <= 199) {
                //     await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}弑神排名第${i + 1}奖励`, [[reward[3], 1]], 0, 0)
                // } else {
                //     await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}弑神排名第${i + 1}奖励`, [[reward[4], 1]], 0, 0)
                // }
                if (i % 200 == 0) {
                    await utils.setTimeout(20)
                }
            }
            redisHandle.del(app.config.gameName + 'worldBossRank' + serverID)
        }
        console.log('世界boss结束')
    }

    createPowerRankRewardByServerID = async (serverID) => {
        let time = moment().add(-1, 'days').valueOf()
        let reward = app.config.reward.totalPower
        let dateStr = moment().format('MM-DD')
        this.powerRankArray[serverID] = []
        this.powerRankData[serverID] = {}
        let length = 500
        let size = 500
        let page = 0
        let players = []
        while (length >= size) {
            let docs = await mongodbHandle.playerDao.findByPageAndSort({
                currentServerID: Number(serverID),
                "cheat": false,
                "loginTime": {
                    $gt: time
                },
                "arena": true,
            }, {
                "totalPower": -1
            }, page * size, size)
            length = docs.length
            for (let i = 0; i < docs.length; i++) {
                let doc = docs[i]
                let pID = doc._id.toString()
                players.push(pID)
            }
            page += 1
        }

        for (let i = 0; i < players.length; i++) {
            let pID = players[i]
            // if (i == 0) {
            //     // await mongodbHandle.mailDao.newAndSave(pID, `${dateStr}战斗力排名第${i + 1}奖励.寄语:站在巅峰的神`, [[reward[0], 1]], 0, 0)
            //     await mongodbHandle.mailDao.newAndSave(pID, `重发${dateStr}战斗力排名第${i + 1}奖励.寄语:站在巅峰的神`, [[reward[0], 1]], 0, 0)
            // } else if (i >= 1 && i <= 10) {
            //     await mongodbHandle.mailDao.newAndSave(pID, `重发${dateStr}战斗力排名第${i + 1}奖励`, [[reward[1], 1]], 0, 0)
            // } else if (i >= 11 && i <= 50) {
            //     await mongodbHandle.mailDao.newAndSave(pID, `重发${dateStr}战斗力排名第${i + 1}奖励`, [[reward[2], 1]], 0, 0)
            // } else if (i >= 51 && i <= 200) {
            //     await mongodbHandle.mailDao.newAndSave(pID, `重发${dateStr}战斗力排名第${i + 1}奖励`, [[reward[3], 1]], 0, 0)
            // } else {
            //     await mongodbHandle.mailDao.newAndSave(pID, `重发${dateStr}战斗力排名第${i + 1}奖励`, [[reward[4], 1]], 0, 0)
            // }
            if (i % 20 == 0) {
                await utils.setTimeout(150)
                console.log("战斗力" + i, players.length)
            }
        }
        console.log("战斗力发放完毕")
    }

    createArenaRankRewardByServerID = async (serverID) => {
        let time = moment().add(RankDay, 'days').valueOf()
        let reward = app.config.reward.arenaScore
        let dateStr = moment().format('MM月DD号')
        this.powerRankArray[serverID] = []
        this.powerRankData[serverID] = {}
        let size = 500
        let length = size
        let page = 0
        let players = []
        while (length >= size) {
            let docs = await mongodbHandle.playerDao.findByPageAndSort({
                currentServerID: Number(serverID),
                "cheat": false,
                "loginTime": {
                    $gt: time
                },
                "arena": true,
            }, {
                "arenaScore": -1,
            }, page * size, size)
            console.log("竞技" + page, docs.length)
            length = docs.length
            for (let i = 0; i < length; i++) {
                let doc = docs[i]
                let pID = doc._id.toString()
                players.push([pID, doc.loginTime])
            }
            page += 1
        }
        let rankTime = moment().add(-7, 'days').valueOf()
        for (let i = 0; i < players.length; i++) {
            let rank = i
            let loginTime = players[i][1]
            if (loginTime > rankTime) {
                let pID = players[i][0]
                // if (rank == 0) {
                //     //.寄语:没一个能打的
                //     await mongodbHandle.mailDao.newAndSave(pID, `重发${dateStr}竞技排名第${rank + 1}奖励.寄语:没一个能打的`, [[reward[0], 1]], 0, 0)
                // } else if (rank >= 1 && rank <= 9) {
                //     await mongodbHandle.mailDao.newAndSave(pID, `重发${dateStr}竞技排名第${rank + 1}奖励`, [[reward[1], 1]], 0, 0)
                // } else if (rank >= 10 && rank <= 49) {
                //     await mongodbHandle.mailDao.newAndSave(pID, `重发${dateStr}竞技排名第${rank + 1}奖励`, [[reward[2], 1]], 0, 0)
                // } else if (rank >= 50 && rank <= 199) {
                //     await mongodbHandle.mailDao.newAndSave(pID, `重发${dateStr}竞技排名第${rank + 1}奖励`, [[reward[3], 1]], 0, 0)
                // } else {
                //     await mongodbHandle.mailDao.newAndSave(pID, `重发${dateStr}竞技排名第${rank + 1}奖励`, [[reward[4], 1]], 0, 0)
                // }
            }
            if (i % 200 == 0) {
                await utils.setTimeout(20)
            }
        }
        console.log("竞技发放完毕")
    }

    createMapProgressRankRewardByServerID = async (env, serverID) => {
        let reward = app.config.reward.mapProgress
        let dateStr = moment().format('MM月DD号')
        let time = moment().add(RankDay, 'days').valueOf()
        let size = 500
        this.powerRankArray[serverID] = []
        this.powerRankData[serverID] = {}
        let length = size
        let page = 0
        let players = []
        console.log('冒险' + serverID + '服')
        while (length >= size) {
            let docs = await mongodbHandle.playerDao.findByPageAndSort({
                currentServerID: Number(serverID),
                "cheat": false,
                "loginTime": {
                    $gt: time
                },
                "mapProgressMax": {
                    $gt: 200100000000
                },
            }, {
                "mapProgressMax": -1,
            }, page * size, size)
            length = docs.length
            for (let i = 0; i < length; i++) {
                let doc = docs[i]
                let pID = doc._id.toString()
                players.push([pID, doc.loginTime])
            }
            page += 1
        }
        let rankTime = moment().add(-7, 'days').valueOf()
        for (let i = 0; i < players.length; i++) {
            let rank = i
            let loginTime = players[i][1]
            if (loginTime > rankTime) {
                let pID = players[i][0]
                // if (rank == 0) {
                //     //.寄语:没一个能打的
                //     await mongodbHandle.mailDao.newAndSave(pID, `重发${dateStr}冒险进度排名第${rank + 1}奖励`, null, null)
                // } else if (rank >= 1 && rank <= 9) {
                //     await mongodbHandle.mailDao.newAndSave(pID, `重发${dateStr}冒险进度排名第${rank + 1}奖励`, [[reward[1], 1]], 0, 0)
                // } else if (rank >= 10 && rank <= 49) {
                //     await mongodbHandle.mailDao.newAndSave(pID, `重发${dateStr}冒险进度排名第${rank + 1}奖励`, [[reward[2], 1]], 0, 0)
                // } else if (rank >= 50 && rank <= 199) {
                //     await mongodbHandle.mailDao.newAndSave(pID, `重发${dateStr}冒险进度排名第${rank + 1}奖励`, [[reward[3], 1]], 0, 0)
                // } else {
                //     await mongodbHandle.mailDao.newAndSave(pID, `重发${dateStr}冒险进度排名第${rank + 1}奖励`, [[reward[4], 1]], 0, 0)
                // }
            }
            if (i % 200 == 0) {
                await utils.setTimeout(20)
            }
        }
        console.log('冒险排行发放完毕')
    }

    createWorldBossRankRewardByServerID = async (env, serverID) => {
        let serverList = await this.getServerList()
        let reward = app.config.reward.worldBoss
        let dateStr = moment().format('MM-DD')

        let data = await redisHandle.zrevrange(app.config.gameName + 'worldBossRank' + serverID, 0, -1)
        console.log("世界boss", data.length)
        for (let i = 0; i < data.length; i++) {
            let pID = data[i]
            // if (i == 0) {
            //     //.寄语:让我来毁灭一切
            //     await mongodbHandle.mailDao.newAndSave(pID, `发放${dateStr}世界boss排名第${i + 1}奖励.寄语:让我来毁灭一切`, [[reward[0], 1]], 0, 0)
            // } else if (i >= 1 && i <= 10) {
            //     await mongodbHandle.mailDao.newAndSave(pID, `发放${dateStr}世界boss排名第${i + 1}奖励`, [[reward[1], 1]], 0, 0)
            // } else if (i >= 11 && i <= 50) {
            //     await mongodbHandle.mailDao.newAndSave(pID, `发放${dateStr}世界boss排名第${i + 1}奖励`, [[reward[2], 1]], 0, 0)
            // } else if (i >= 51 && i <= 200) {
            //     await mongodbHandle.mailDao.newAndSave(pID, `发放${dateStr}世界boss排名第${i + 1}奖励`, [[reward[3], 1]], 0, 0)
            // } else {
            //     await mongodbHandle.mailDao.newAndSave(pID, `发放${dateStr}世界boss排名第${i + 1}奖励`, [[reward[4], 1]], 0, 0)
            // }
            // if (i % 15 == 0) {
            //     await utils.setTimeout(150)
            // }
        }
        redisHandle.del(app.config.gameName + 'worldBossRank' + serverID)
        console.log("世界boss发放完毕")
    }
}

let rankHandle = new RankHandle()
export default rankHandle

